package com.cdp.web.controller.system;

import com.alibaba.fastjson.JSONArray;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.cdp.common.core.domain.AjaxResult;
import com.cdp.common.core.domain.entity.SysFileAudit;
import com.cdp.common.core.domain.entity.SysPkl;
import com.cdp.common.utils.SecurityUtils;
import com.cdp.common.utils.StringUtils;
import com.cdp.system.dto.AnalysisJsonDTO;
import com.cdp.system.dto.FileAuditDTO;
import com.cdp.system.dto.saveModelDTO;
import com.cdp.system.service.ISysFileAuditService;
import com.cdp.system.service.ISysPklService;
import com.cdp.system.vo.SysFileAuditVo;
import com.cdp.system.vo.SysPklV2VO;
import com.cdp.system.vo.SysPklVO;
import com.fasterxml.jackson.databind.ObjectMapper;
import lombok.extern.slf4j.Slf4j;
import org.apache.ibatis.annotations.Param;
import org.checkerframework.checker.units.qual.A;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;

import javax.validation.Valid;
import java.io.BufferedReader;
import java.io.FileReader;
import java.io.IOException;
import java.time.LocalDateTime;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;

@RestController
@RequestMapping
@Slf4j
public class PklController {


    @Autowired
    private ISysPklService sysPklService;
    @Autowired
    private ISysFileAuditService sysFileAuditService;



    @PostMapping("/saveModel")
    public AjaxResult saveModel(@RequestBody saveModelDTO saveModelDTO) {
        List<Double> yTest1 = saveModelDTO.getYTest();//实际值
        List<Double> yFredFinslTest1 = saveModelDTO.getYFredFinslTest();//预测值


        List<String> inputFeatures = saveModelDTO.getInputFeatures();
        List<String> targetFeature = saveModelDTO.getTargetFeature();
        Map<String, List<Double>> paramGrid = saveModelDTO.getParamGrid();
        Integer selectionLater = saveModelDTO.getSelectionLater();

        SysPkl sysPkl = new SysPkl();
        //记录入参

        sysPkl.setModelName(saveModelDTO.getRecordName());
        sysPkl.setInputFeatures(String.valueOf(inputFeatures));
        sysPkl.setTargetFeature(String.valueOf(targetFeature));
        sysPkl.setParamGrid(String.valueOf(paramGrid));
        sysPkl.setSelectionLater(String.valueOf(selectionLater));
        sysPkl.setPklUrl(saveModelDTO.getModelPklPath());
        //统计分析入参
        sysPkl.setSelectFeature(String.valueOf(saveModelDTO.getSelectFeature()));
        sysPkl.setXlsxFile(saveModelDTO.getXlsxFile());
        sysPkl.setFirstTargetFeature(saveModelDTO.getFirstTargetFeature());
        sysPkl.setRecordName(saveModelDTO.getRecordName());
        sysPkl.setExcelName(saveModelDTO.getExcelName());
        Long userId = SecurityUtils.getUserId();


        sysPkl.setModel(saveModelDTO.getRecordName());


//        List<String> targetFeature1 = saveModelDTO.getTargetFeature();
//        String s = targetFeature1.get(0);
//        String cleanTarget = s.replaceAll("[\\[\\]]", "").trim();
//        sysPkl.setTarget(cleanTarget);

        List<String> targetFeature1 = saveModelDTO.getTargetFeature();
        String s = (targetFeature1 != null && !targetFeature1.isEmpty()) ? targetFeature1.get(0) : "";
        String cleanTarget = s.replaceAll("[\\[\\]]", "").trim(); // 去掉中括号
        String[] fields = cleanTarget.split("\\s*,\\s*");          // 分割
        String firstField = fields.length > 0 ? fields[0] : "";    // 取第一个字段
        sysPkl.setTarget(firstField);




        sysPkl.setNumber(String.valueOf(saveModelDTO.getInputFeatures().size()));

        // 将 List<String> 转换为用顿号隔开的字符串
        String inputFeatures2 = String.join("、", saveModelDTO.getInputFeatures());

// 设置到字段中
        sysPkl.setDetail(inputFeatures2);




        Integer reta = saveModelDTO.getSelectionLater();
        if (reta == 1) {
            sysPkl.setPercentage("9:1");
        } else if (reta == 2) {
            sysPkl.setPercentage("8:2");
        } else if (reta == 3) {
            sysPkl.setPercentage("7:3");
        } else if (reta == 4) {
            sysPkl.setPercentage("6:4");
        }

        sysPkl.setR2(saveModelDTO.getR2());
        sysPkl.setMse(saveModelDTO.getMse());
       // sysPkl.setImageUrl(saveModelDTO.getImageUrl());


        if (userId == null) {
            log.error("获取userId失败");
            return AjaxResult.error("获取userId失败");
        }
        // 设置其他字段
        sysPkl.setUserId(userId);
        sysPkl.setCreateTime(LocalDateTime.now());


        sysPkl.setYTest(String.valueOf(yTest1));
        sysPkl.setYPredFinalTest(String.valueOf(yFredFinslTest1));
        System.out.println("yTest1" + String.valueOf(yTest1));
        System.out.println("yFredFinslTest1" + String.valueOf(yFredFinslTest1));
        // 保存 SysPkl 到数据库
        try {
            sysPklService.save(sysPkl);
        } catch (Exception e) {
            log.error("保存pkl失败", e);
            return AjaxResult.error("保存失败", e);

        }

        return AjaxResult.success();
    }


    /**
     * 查询用户个人模型
     */


    /**
     * 查询个人模型
     * @return
     */

    @PostMapping("queryPklByUserId")
    public AjaxResult querySysPklByUserId(@RequestBody FileAuditDTO fileAuditDTO) {
        Long userId = SecurityUtils.getUserId();
        if (userId == null) {
            return AjaxResult.error("获取用户id异常，请重试！");
        }
/*        LambdaQueryWrapper<SysPkl> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(SysPkl::getUserId, userId);
        queryWrapper.eq(SysPkl::getDeleteTime, 0);
        queryWrapper.orderByDesc(SysPkl::getCreateTime);*/
        List<SysPkl> list = sysPklService.querySysPklByUserId(fileAuditDTO);

        List<SysPklV2VO> lists = new ArrayList<>();
        for (SysPkl sysPkl : list) {
            SysPklV2VO sysPklVO = new SysPklV2VO();
            BeanUtils.copyProperties(sysPkl, sysPklVO);
            lists.add(sysPklVO);
        }
        return AjaxResult.success(lists);
    }


    /**
     * 查询我的入库申请
     */

    @PostMapping("queryFileAuditByUserId")
    public AjaxResult queryFileAuditByUserId(@RequestBody FileAuditDTO fileAuditDTO) {
        Long userId = SecurityUtils.getUserId();
        if (userId == null) {
            System.out.println("获取id"+userId);
            return AjaxResult.error("获取用户id异常，请重试！");
        }
        fileAuditDTO.setUserId(userId);
        List<SysFileAudit> list = sysFileAuditService.queryFileAuditByUserId(fileAuditDTO);

        List<SysFileAuditVo> arrayList = new ArrayList<>();
        for (SysFileAudit fileAudit : list) {
            SysFileAuditVo sysFileAuditVo = new SysFileAuditVo();
            BeanUtils.copyProperties(fileAudit,sysFileAuditVo);
            Integer status = fileAudit.getStatus();
            switch (status){
                case 0:
                    sysFileAuditVo.setStatusStr("待审核");
                    break;
                case 1:
                    sysFileAuditVo.setStatusStr("审核通过");
                    break;
                case 2:
                    sysFileAuditVo.setStatusStr("审核未通过");
                    break;
                default:
                    sysFileAuditVo.setStatusStr("未知状态");
                    break;
            }
            Integer tableName = fileAudit.getTableName();
            /**
             * 1： 水泥
             * 2： 砂
             * 3： 石
             * 4： 粉煤灰
             * 5： 减水剂
             * 6： 增效剂
             * 7：力学性能
             * 8：变形性能
             * 9：耐久性能
             *
             *
             * 10:水
             * 11:矿粉
             * 12：其他参合料.
             * 13:膨胀剂
             14坍落度
             */
            switch (tableName) {
                case 1:
                    sysFileAuditVo.setTableNameStr("水泥");
                    break;
                case 2:
                    sysFileAuditVo.setTableNameStr("砂");
                    break;
                case 3:
                    sysFileAuditVo.setTableNameStr("石");
                    break;
                case 4:
                    sysFileAuditVo.setTableNameStr("粉煤灰");
                    break;
                case 5:
                    sysFileAuditVo.setTableNameStr("减水剂");
                    break;
                case 6:
                    sysFileAuditVo.setTableNameStr("增效剂");
                    break;
                case 7:
                    sysFileAuditVo.setTableNameStr("抗压强度");
                    break;
                case 8:
                    sysFileAuditVo.setTableNameStr("变形性能");
                    break;
                case 9:
                    sysFileAuditVo.setTableNameStr("耐久性能");
                    break;
                case 10:
                    sysFileAuditVo.setTableNameStr("水");
                    break;
                case 11:
                    sysFileAuditVo.setTableNameStr("矿粉");
                    break;
                case 12:
                    sysFileAuditVo.setTableNameStr("其他参合料");
                    break;
                case 13:
                    sysFileAuditVo.setTableNameStr("膨胀剂");
                    break;
                case 14:
                    sysFileAuditVo.setTableNameStr("坍落度");
                    break;
                default:
                    sysFileAuditVo.setTableNameStr("未知类型");
                    break;
            }

            arrayList.add(sysFileAuditVo);
        }

        return AjaxResult.success(arrayList);
    }





/*
    @PostMapping("/saveModel")
    public AjaxResult saveModel(@RequestBody saveModelDTO saveModelDTO){
        List<Double> yTest1 = saveModelDTO.getYTest();//实际值
        List<Double> yFredFinslTest1 = saveModelDTO.getYFredFinslTest();//预测值
        String modelName = saveModelDTO.getModelPklPath();
        List<String> inputFeatures = saveModelDTO.getInputFeatures();
        List<String> targetFeature = saveModelDTO.getTargetFeature();
        Map<String, List<Double>> paramGrid = saveModelDTO.getParamGrid();
        Integer selectionLater = saveModelDTO.getSelectionLater();

        SysPkl sysPkl = new SysPkl();
        //记录入参
        sysPkl.setModelName(modelName);
        sysPkl.setInputFeatures(String.valueOf(inputFeatures));
        sysPkl.setTargetFeature(String.valueOf(targetFeature));
        sysPkl.setParamGrid(String.valueOf(paramGrid));
        sysPkl.setSelectionLater(String.valueOf(selectionLater));
        sysPkl.setPklUrl(saveModelDTO.getModelPklPath());
      //统计分析入参
        sysPkl.setSelectFeature(String.valueOf(saveModelDTO.getSelectFeature()));
        sysPkl.setXlsxFile(saveModelDTO.getXlsxFile());
        sysPkl.setFirstTargetFeature(saveModelDTO.getFirstTargetFeature());
        sysPkl.setRecordName(saveModelDTO.getRecordName());
        sysPkl.setExcelName(saveModelDTO.getExcelName());
        Long userId = SecurityUtils.getUserId();
        if(userId==null){
            log.error("获取userId失败");
            return AjaxResult.error("获取userId失败");
        }
        // 设置其他字段
        sysPkl.setUserId(userId);
        sysPkl.setCreateTime(LocalDateTime.now());


        sysPkl.setYTest(yTest1.toString());
        sysPkl.setYPredFinalTest(yFredFinslTest1.toString());

        // 保存 SysPkl 到数据库
        try {
            sysPklService.save(sysPkl);
        } catch (Exception e) {
            log.error("保存pkl失败", e);
            return AjaxResult.error("保存失败",e);

        }

        return AjaxResult.success();
    }
*/



    /**
     * 校验名称是否重复
     *
     * @param name
     * @return
     */
    @GetMapping("checkoutRecordName")
    public AjaxResult checkoutRecordName(@RequestParam("name") String name) {
        if (StringUtils.isEmpty(name)) {
            log.error("checkoutRecordName接口，name为空");
            return AjaxResult.error("name为空，请重试");
        }
        LambdaQueryWrapper<SysPkl> wrapper = new LambdaQueryWrapper<>();
        // 设置查询条件：名字等于传入的名字
        wrapper.eq(SysPkl::getRecordName, name);

        // 查询数据库，检查是否有相同名字的记录
        SysPkl sysPkl = sysPklService.getOne(wrapper, false);
        // 如果sysPkl不为null，说明数据库中已经有重复的名字
        if (sysPkl != null) {

            return new AjaxResult(510, "名称已经存在，请输入其他模型名称！");
//            return AjaxResult.error("名称已经存在，请输入其他模型名称！");
        } else {
            return AjaxResult.success();
        }
    }


    /**
     * 根据json地址解析json
     */
    @PostMapping("analysisJson")
    public AjaxResult analysisJson(@Validated @RequestBody AnalysisJsonDTO analysisJsonDTO) {
        String jsonUrl = analysisJsonDTO.getJsonUrl();

        StringBuilder jsonContent = new StringBuilder();
        try (BufferedReader reader = new BufferedReader(new FileReader(jsonUrl))) {
            String line;
            while ((line = reader.readLine()) != null) {
                jsonContent.append(line);
            }

            List<List> rawList = JSONArray.parseArray(jsonContent.toString(), List.class);
            List<List<String>> excelData = convertToListOfString(rawList);

            return AjaxResult.success("解析成功", excelData);

        } catch (IOException e) {
            e.printStackTrace();
            log.error("解析JSON失败"+ e.getMessage());
            return AjaxResult.error("读取文件失败: " + e.getMessage());
        } catch (Exception e) {
            e.printStackTrace();
            log.error("解析JSON失败"+ e.getMessage());
            return AjaxResult.error("解析JSON失败: " + e.getMessage());
        }
    }

    private List<List<String>> convertToListOfString(List<List> rawList) {
        List<List<String>> result = new ArrayList<>();
        for (List item : rawList) {
            List<String> subList = new ArrayList<>();
            for (Object obj : item) {
                subList.add(String.valueOf(obj));
            }
            result.add(subList);
        }
        return result;
    }


}
